import types, re

from django.http import HttpResponse
from django.http import Http404

# Google Gadgets
def gadget(request, path='', module=None, userprefs_from_params=False, **kwargs):
    mod = module()

    if not mod.url:
        mod.url = request.path

    # Gadget XML
    if not path or path == 'as.xml':
        if userprefs_from_params and kwargs:
            mod.get_userprefs_values(kwargs)

        ret = HttpResponse(mod.render())

    # Messages XML
    elif path.startswith('messages/'):
        m = re.match('^messages/([a-zA-Z]{2,3})_([A-Z]{2,3})\.xml', path)

        if m:
            lang = m.group(1)
            country = m.group(2)
        else:
            lang = country = None

        loc = mod.get_locale(lang, country)
        messages_rendered = type(loc.messages) == types.StringType and loc.messages or loc.messages.render()
        ret = HttpResponse(messages_rendered)

    # Raises "not found"
    else:
        raise Http404()

    ret['content-type'] = 'application/xml'
    
    return ret

